package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ShopTypeMapper shopTypeMapper;
    @Override
    public List<ShopType> queryTypeList() {
        //1.查询redis
        List<String> list = stringRedisTemplate.opsForList().range(CACHE_SHOPTYPE_KEY, 0, -1);

        //2.如果redis中存在，直接返回
        if(!list.isEmpty()){
            List<ShopType> collect = list.stream().map(item -> {
                ShopType shopType = JSONUtil.toBean(item, ShopType.class);
                return shopType;
            }).collect(Collectors.toList());
            return collect;
        }

        //3.如果不存在查询数据库
//        LambdaQueryWrapper<ShopType> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.orderByAsc(ShopType::getSort);
//        List<ShopType> shopTypes = shopTypeMapper.selectList(queryWrapper);
        List<ShopType> shopTypes = query().orderByAsc("sort").list();

        //5.更新redis
        List<String> collect = shopTypes.stream().map(item -> {
            String jsonItem = JSONUtil.toJsonStr(item);
            return jsonItem;
        }).collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(CACHE_SHOPTYPE_KEY, collect);

        //6.返回list
        return shopTypes;
    }
}
